package com.xiaomei.manager.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.xiaomei.manager.model.Broadcast;
import com.xiaomei.manager.model.BroadcastRecord;
import com.xiaomei.manager.model.User;
import com.xiaomei.manager.service.IBroadcastService;
import com.xiaomei.manager.service.IUserService;
import com.xiaomei.manager.utils.Constants;
import com.xiaomei.manager.utils.OSSClientUtils;
import com.xiaomei.manager.web.aliyun.OSS.AliyunUpload;
import com.xiaomei.manager.web.dto.req.BroadcastDto;
import com.xiaomei.manager.web.dto.req.CommentDto;
import com.xiaomei.manager.web.page.Page;

@Controller
@RequestMapping("/broadcast")
public class BroadcastController {

	@Autowired
	private IBroadcastService broadcastService;
	
	@Autowired
	private IUserService userService;
	
	@RequiresPermissions("broadcast:view")
	@RequestMapping()
	public String listBroadcast(Model model, BroadcastDto dto, Page<Broadcast> page) {
		page.setParamDto(dto);
		broadcastService.selectBroadcastForPage(page);
		model.addAttribute("page", page);
		model.addAttribute("dto", dto);
		return "/broadcast/list";
	}
	
	@RequiresPermissions("broadcast:create")
	@RequestMapping( value = "/create",method = RequestMethod.GET)
	public String initAddForm(Model model) {
		model.addAttribute("ban", new Broadcast());
        model.addAttribute("op", "新增");
        return "broadcast/add";
	}
	
	@RequiresPermissions("broadcast:create")
	@RequestMapping( value = "/create",method = RequestMethod.POST)
	public String addForm(Broadcast broadcast, @RequestParam("files") MultipartFile[] files, String userCode_ck, CommentDto comments) {
		
		StringBuffer sb = new StringBuffer();
		
		/**
		 * 获取虚拟用户
		 */
		List<User> userLst = userService.selectFictitiousUser();
		
		Random random = new Random();
		if("1".equals(userCode_ck)) { // 男
			while(true) {
				User user = userLst.get(random.nextInt(userLst.size()));
				if("男".equals(user.getSex())) {
					broadcast.setUserCode(user.getUserCode());
					break;
				}
			}
		} else if("2".equals(userCode_ck)) { // 女
			while(true) {
				User user = userLst.get(random.nextInt(userLst.size()));
				if("女".equals(user.getSex())) {
					broadcast.setUserCode(user.getUserCode());
					break;
				}
			}
		}
		
		// 上传图片
		if(files != null && files.length > 0 && files[0].getSize() > 0) {
			long millis = System.currentTimeMillis() / 1000;
			for(int i=0; i<files.length; i++) {
				MultipartFile file = files[i];
				
				try {
					BufferedImage buff = ImageIO.read(file.getInputStream());
					int width = buff.getWidth();
					int height = buff.getHeight();
					
					String suffix = OSSClientUtils.getSuffixByFilename(file.getOriginalFilename());
					String filename = broadcast.getUserCode() + "/broadcast/" + millis + "/img" + (i + 1) + "_" + width + "X" + height + "." + suffix;

					if(AliyunUpload.uploadMultipartFile(filename, Constants.OSS_BUCKET_COMMON, file)) {
						String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, filename);
						sb.append(url);
					}
					
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(i+1 < files.length) {
					sb.append(",");
				}
			}
		}
		broadcast.setBroadcastImg(sb.toString());
		broadcast.setCommentCount(comments.getUserCode_ck1() == null ? 0 : comments.getUserCode_ck1().length);
		broadcastService.addBroadcast(broadcast);
		
		// 保存评价列表
		if(comments.getUserCode_ck1() != null && comments.getUserCode_ck1().length > 0) {
			String[] userCode_ck1 = comments.getUserCode_ck1();
			String[] userCode = comments.getUserCode1();
			Integer[] fabulousCount = comments.getR_fabulousCount();
			String[] commentContent = comments.getCommentContent();
			Timestamp[] commentTime = comments.getCommentTime();
			
			for(int i=0; i<userCode_ck1.length; i++) {
				BroadcastRecord record = new BroadcastRecord();
				record.setAcceptCode(broadcast.getUserCode());
				record.setBroadcastId(broadcast.getId());
				record.setSuperiorId(0);
				record.setState("0");
				record.setFabulousCount(fabulousCount[i]);
				record.setCommentContent(commentContent[i]);
				record.setCommentTime(commentTime[i]);
				
				if("1".equals(userCode_ck1[i])) { // 男
					while(true) {
						User user = userLst.get(random.nextInt(userLst.size()));
						if("男".equals(user.getSex()) && !(user.getUserCode().equals(broadcast.getUserCode()))) {
							record.setSponsorCode(user.getUserCode());
							break;
						}
					}
				} else if("2".equals(userCode_ck1[i])) { // 女
					while(true) {
						User user = userLst.get(random.nextInt(userLst.size()));
						if("女".equals(user.getSex()) && !(user.getUserCode().equals(broadcast.getUserCode()))) {
							record.setSponsorCode(user.getUserCode());
							break;
						}
					}
				} else {
					record.setSponsorCode(userCode[i]);
				}
				broadcastService.insertBroadcastRecord(record);
			}
		}
		
		return "redirect:/broadcast";
	}
	
	@RequiresPermissions("broadcast:modify")
	@RequestMapping( value = "/modify",method = RequestMethod.GET)
	public String initModifyForm(Integer id, Model model) {
		Broadcast broadcast = broadcastService.getBroadcastById(id);
		List<BroadcastRecord> recordLst = broadcastService.selectByBroadcastId(id);
		model.addAttribute("recordLst", recordLst);
		model.addAttribute("broadcast", broadcast);
		model.addAttribute("imgArr", imgbrDto(broadcast));
        model.addAttribute("op", "修改");
        return "broadcast/edit";
	}
	
	@RequiresPermissions("broadcast:modify")
	@RequestMapping( value = "/modify",method = RequestMethod.POST)
	public String modify(Broadcast broadcast,CommentDto comments) {
		if(comments.getUserCode1() != null && comments.getUserCode1().length > 0) {
			
			String[] userCode = comments.getUserCode1();
			Integer[] fabulousCount = comments.getR_fabulousCount();
			String[] commentContent = comments.getCommentContent();
			Timestamp[] commentTime = comments.getCommentTime();
			for(int i=0; i<userCode.length; i++) {
				BroadcastRecord record = new BroadcastRecord();
				record.setAcceptCode(userCode[i]);
				record.setBroadcastId(broadcast.getId());
				record.setSuperiorId(0);
				record.setState("0");
				record.setFabulousCount(fabulousCount[i]);
				record.setCommentContent(commentContent[i]);
				record.setCommentTime(commentTime[i]);
				record.setSponsorCode(userCode[i]);
				broadcastService.insertBroadcastRecord(record);
				broadcastService.updateCommentCount(broadcast.getId());
			}
		
		broadcastService.modifyBroadcastById(broadcast);
		}
		return "redirect:/broadcast";
	}
	
	/**
	 * 图片转换
	 * @param
	 */
	private String[] imgbrDto(Broadcast broadcast) {
		String imgString = broadcast.getBroadcastImg();
		if(!StringUtils.isEmpty(imgString)) {
			String[] imgArr = imgString.split(",");
			for(int i=0; i<imgArr.length; i++) {
				imgArr[i] += "?x-oss-process=image/resize,h_200";
			}
			return imgArr;
		}
		return new String[] {};
	}

	@RequiresPermissions("broadcast:disable")
	@RequestMapping( value = "/disable",method = RequestMethod.GET)
	public String disableBroadcast(Integer id) {
		broadcastService.disableBroadcastById(id);
		
		return "redirect:/broadcast";
	}
	

	@RequiresPermissions("broadcast:disable")
	@RequestMapping( value = "/record/modify",method = RequestMethod.GET)
	public String disableBroadcastRecord(Integer broadcastId, Integer id) {
		broadcastService.disableBroadcastRecordById(broadcastId, id);
		
		return "redirect:/broadcast/modify?id=" + broadcastId;
	}
}
